<?php
/*
 * @Author: 孙开源 && sunkaiyuan@namenode.cn
 * @Date: 2023-04-12 16:45:39
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @LastEditTime: 2023-07-19 17:11:18
 * @Description: 拦截器
 * 
 */
namespace zhijingfeisuo\Kernel\Services;

use zhijingfeisuo\Kernel\Exceptions;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;

class Interceptor
    {
    /**
     * @var \zhijingfeisuo\Application
     */
    protected $app;


    public function __construct($app)
        {
        $this->app = $app;
        }


    public function request(RequestInterface $request) : RequestInterface
        {
        return $request->withHeader('authen-type', 'V2')
            ->withHeader('clientId', $this->app['config']->get('clientId'))
            ->withHeader('orgCode', $this->app['config']->get('orgCode'))
            ->withHeader('userId', $this->app['cacher']->get('userId'));
        }

    //返回true  会将访问重试
    public function response(ResponseInterface $response, RequestInterface $request, $retries) : bool
        {
        if (is_null($response) || $retries < 1) {
            return false;
            }

        $response = json_decode($response->getBody(), true);

        if (in_array($response['code'] ?? null, ['UAC0002'])) {
            $this->app->access_token->refreshToken();
            return true;
            }
        else if (in_array($response['code'] ?? null, ['UAC0003'])) {
            $this->app->access_token->refresh();
            return true;
            }
        else if (in_array($response['code'] ?? null, ['IC_CARD_IN_PRODUCT', 'WORKORDER_ISSUE_FAID'])) {
            throw new Exceptions\InvalidArgumentException($response['message'], 500);
            }
        else if (in_array($response['code'] ?? null, ['400', 'ErrSystem', 'ErrBusiness'])) {
            throw new Exceptions\InvalidArgumentException($response['msg'], 500);
            }
        else if (($response['successful'] ?? true) === false) {

            if (in_array($response['responseInfo']['code'] ?? null, ['UAC0291', 'UAC0006', 'UAC0004', '', 'UAC0007', 'SYS0002']))
                throw new Exceptions\InvalidArgumentException($response['responseInfo']['tips']);
            else
                throw new Exceptions\HttpException("未知错误:" . $response['responseInfo']['code']);
            }

        return false;
        }
    }